<template>
  <div class="message">
    <heads title="聊一聊"></heads>
    <van-pull-refresh v-model="isLoading" @refresh="getData" v-if="list">
       <van-empty v-if="!hasMore" description="没有更多数据了~" />
   <ul ref="list" class="list flex">
      
      <li v-for="(item, index) in list" :key="index">
        <p class="time">
          <span>{{ item.reqTime }}</span>
        </p>
        <div class="main flex" :class="{ self: item.self }">
          <!-- <img
            class="avatar"
            width="30"
            height="30"
            :src="item.avatar"
          /> -->
          <van-image class="avatar" round width="30" fit="cover" height="30" :src="item.avatar" />
          <div class="text" :class="item.msgType === 1 ? 'textImg' : ''" :style="{backgroundImage:item.msgType === 1 ? 'url('+item.msg+')' : ''}">{{ item.msgType === 0 && item.msg!=='' ? item.msg :'' }}</div>

        </div>
      </li>
    </ul>
</van-pull-refresh>
 
    <div class="place-holder" :style="{ height: height }"></div>
    <div class="btn-box" ref="footer">
      <div class="flex">
        <van-uploader :after-read="uploadForehead">
          <van-icon name="photo-o" size="30" color="#999" />
        </van-uploader>

        <van-icon name="smile-o" size="30" color="#999" @click="emitShow" />
        <van-field
          v-model="content"
          :border="false"
          label=""
          placeholder="请输入内容"
        />
        <van-button type="info" round class="btn-common" @click="send">
          发送
        </van-button>
      </div>
      <picker
        v-if="emotion"
        :include="['people']"
        :showSearch="false"
        :showPreview="false"
        :showCategories="false"
        :native="false"
        @select="addEmoji"
      />
      
    </div>
  </div>
</template>
<script>
import Vue from 'vue'
import { mapState } from 'vuex'
import { Picker } from "emoji-mart-vue"; //引入组件
import { PullRefresh,Dialog,Toast  } from 'vant';
// import VEmojiPicker from 'v-emoji-picker';
Vue.use(PullRefresh);
import ReconnectingWebSocket from 'reconnecting-websocket';
export default {
  components: {
    heads: resolve => require(["@/components/common/heads"], resolve),
    Picker,
  },
  data() {
    return {
        isLoading: true,
      pageNo:1,
      pageSize:10,
      content: "",
      emotion: false,
      height: "",
      websock: null,
      user:null,
      hasMore:true,
      list: [
        // {
        //   date: "2020-10-11",
        //   self: true,
        //   msg: "https://img.yzcdn.cn/vant/cat.jpeg",
        //   msgType:0,
        //   img: "https://img.yzcdn.cn/vant/cat.jpeg"
        // },
        
      ]
    };
  },
    computed:{
    ...mapState(['roles','userInfo'])

  },
   watch: {
      //监听list,当有修改的时候进行div的屏幕滚动，确保能看到最新的聊天
      list:{
        handler(newVal,oldVal){
          let _this = this;
        setTimeout(() => {
        
           _this.height = `${_this.$refs.footer.offsetHeight}px`;
            let _container = document.getElementsByClassName("list")[0];
        _container.scrollTop = _container.scrollHeight;
        window.scrollTo(0, _container.scrollHeight);
           _this.$forceUpdate()
           
        }, 100);
   
        //加setTimeout的原因：由于vue采用虚拟dom，我每次生成新的消息时获取到的div的scrollHeight的值是生成新消息之前的值，所以造成每次都是最新的那条消息被隐藏掉了
        },
        immediate:true
        
      }
    },
     mounted() {
      //  this.$nextTick(() => {
      //    this.scrollToBottom()
      //  })
        
    },

    updated(){
        // this.scrollToBottom()
    },
  methods: {
     scrollToBottom() {
            this.$nextTick(() =>{
                this.$refs.list.scrollTop = this.$refs.list.scrollHeight;
            })
        },   
    addEmoji(e) {
      this.content += `${ e.native }`;
    console.log('消息',this.content)
    },
   
    emitShow() {
      let _this = this;
      _this.emotion = !_this.emotion;
      setTimeout(() => {
        _this.height = `${_this.$refs.footer.offsetHeight}px`;
        console.log(_this.$refs.footer.offsetHeight);
      }, 1000);
    },
     //文件上传
    uploadForehead(file) {
      let _this = this;
      let formData = new FormData();
      formData.append("file", file.file);
            this.$ajax
        .post(
          `${this.$baseUrl}/portal/picture/isssue/upload?userId=${_this.userInfo.userId}`,
          formData
        )
        .then(function(res) {
         
          if (res.data.code == 200) {
           
             var message = {
            cmd: "sendTo",
            token: `${ _this.userInfo.tokenHead }${ _this.userInfo.ptToken }`,
            // to: "1",
             to:  `${ _this.$route.params.userId }`,
            msg: res.data.data[0].pictureUrl,
            msgType:1
        }
     
            _this.websocketsend(JSON.stringify(message));

          }
        })
        .catch(function(error) {
         
          console.log(error);
        });
     
     
    },
    logIn(){
        let _this = this;
          var message = {
            cmd : "LOGIN",
            withId:_this.$route.params.userId,
            token : `${ _this.userInfo.tokenHead }${ _this.userInfo.ptToken }`,
            }
             Toast.loading({
              message: '登录...',
              forbidClick: true,
            });
       this.websocketsend(JSON.stringify(message));
       
    },
       logOut(){
        let _this = this;
          var message = {
            cmd : "LOGOUT",
            token : `${ _this.userInfo.tokenHead }${ _this.userInfo.ptToken }`,
            }
            //  Toast.loading({
            //   message: '登录...',
            //   forbidClick: true,
            // });
            console.log('退出登陆中')
       this.websocketsend(JSON.stringify(message));
        this.websock.close() //离开路由之后断开websocket连接
       
    },
    getData(){
         let _this = this;
          var message = {
            cmd: "msgHistoryCmd",
            token : `${ _this.userInfo.tokenHead }${ _this.userInfo.ptToken }`,
            withId: `${ _this.$route.params.userId }`, // 用户id
            type:1, // 默认 1 还有
             pageNo: _this.pageNo,
             pageSize: _this.pageSize,
            }
            _this.isLoading = true
            console.log('查询历史记录参数',message)
             Toast.loading({
              message: '加载中...',
              forbidClick: true,
            });
         this.websocketsend(JSON.stringify(message));
        
    },
    // 发送消息
    send() {
      let _this = this;
      _this.emotion = false;
       var message = {
            cmd: "sendTo",
            token: `${ _this.userInfo.tokenHead }${ _this.userInfo.ptToken }`,
            // to: "1",
             to: `${ _this.$route.params.userId }`,
            msg: _this.content,
             msgType:0
        }
         _this.pageNo = 1
         _this.hasMore = true
         if(_this.content){
           console.log('点击发送',message)
            Toast.loading({
              message: '发送中...',
              forbidClick: true,
            });
            _this.websocketsend(JSON.stringify(message));
         }
     
      
    },
    initWebSocket(){ //初始化weosocket
        const wsuri = "ws://www.rmcypt.com:8666/ws";
        
        this.websock = new ReconnectingWebSocket(wsuri);
        this.websock.timeoutInterval = 54000;
        this.websock.onmessage = this.websocketonmessage;
        this.websock.onopen = this.websocketonopen;
        this.websock.onerror = this.websocketonerror;
        this.websock.onclose = this.websocketclose;
      },
      websocketonopen(){ //连接建立之后执行send方法发送数据
      this.logIn()
       console.log('建立连接')
       
      },
      websocketonerror(e){//连接建立失败重连
      console.log('连接失败',e);
        this.initWebSocket();
      },
      websocketonmessage(e){ //数据接收
      let _this = this
        const redata = JSON.parse(e.data);
        if(redata.user){
            this.user = redata.user
            this.getData()
            return
        }
        Toast.clear();
        if(redata.code === 10002){
            Dialog.confirm({
                title: '提示',
                message: '登录失效，是否重新登录?'
            }).then(() => {
                // on confirm
                _this.$router.push({ path: '/Login' })
            }).catch(() => {
                // on cancel
            });
            return
        }
      
        redata.chatMsgList.map((item,index) => {
           if(item.fromId === _this.userInfo.userId){
           item.self = true
           item.avatar = _this.userInfo.avatar
          }else{
            item.self = false
            item.avatar = decodeURIComponent(_this.$route.params.avatar)
          }
        })
        _this.isLoading = false
        if(redata.chatMsgList.length > 0){
            _this.list = redata.chatMsgList.length == 1 ? redata.chatMsgList.concat(_this.list) : _this.list.concat(redata.chatMsgList)
        // _this.list = redata.chatMsgList.concat(_this.list)

         console.log('接收数据',redata.chatMsgList)
         console.log('数据',_this.list,)
         
        }
        if(redata.chatMsgList.length < _this.pageSize){
          _this.hasMore = false
          return
        }
         
       
          _this.hasMore = true
          _this.pageNo++;
      
       
        
       
      },
      websocketsend(Data){//数据发送
      console.log('发送数据',Data)
     
        this.websock.send(Data);
        // this.getData()
        this.content = ''
         this.emotion = false;
      },
      websocketclose(e){  //关闭
        console.log('连接关闭',e);
      },
  },
  created() {
    let _this = this;
    _this.initWebSocket();

  },
   destroyed() {
     this.logOut()
     
    },
};
</script>

<style lang="scss" scoped>
.message {
  padding: 10px 15px;
  // overflow-y: scroll;
.list{
  overflow: auto;
  display: flex;
    flex-direction: column;
    flex-flow: column-reverse;
}
  li {
    margin-bottom: 15px;
    width: 100%;
  }
  .time {
    margin: 7px 0;
    text-align: center;
    font-size: 0;

    > span {
      display: inline-block;
      padding: 0 18px;
      font-size: 12px;
      color: #999;
      border-radius: 2px;
    }
  }
  .avatar {
    margin: 0 10px 0 0;
     border-radius: 50%;
        border: 1px solid #5bbd97;
  }
  .text {
    // display: inline-block;
    position: relative;
    padding: 5px 10px;
    max-width: calc(100% - 40px);
    min-height: 30px;
    // line-height: 2.5;
    font-size: 12px;
    text-align: left;
    word-break: break-all;
    background-color: #fff;
    border-radius: 4px;
    box-sizing: border-box;
    &.textImg{
         width: 1.4rem;
    height: 1.6rem;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    border-radius: 5px;
    margin: 0;
    &:before{
        display: none;
    }
    }


    &:before {
      content: " ";
      position: absolute;
      top: 9px;
      right: 100%;
      border: 6px solid transparent;
      border-right-color: #fff;
    }
  }
  .main {
    justify-content: flex-start;
    align-items: flex-start;
    &.self {
      // justify-content: flex-end!important;
      text-align: right;
      flex-flow: row-reverse;

      .avatar {
        margin: 0 0 0 10px;
       
      }
      .text {
        background-color: #b2e281;

        &:before {
          right: inherit;
          left: 100%;
          border-right-color: transparent;
          border-left-color: #b2e281;
        }
      }
    }
  }
}

.btn-box {
  background: #fff;
  padding: 0.1rem 0.3rem;
  position: fixed;
  width: 100%;
  box-sizing: border-box;
  left: 0;
  bottom: 0;
  .van-field {
    background: #f7f7f7;
    border-radius: 30px;
    margin-right: 0.3rem;
  }
  /deep/ .van-uploader {
    height: 0.7rem;
    .van-uploader__wrapper {
      height: 100%;
    }
    .van-uploader__input-wrapper {
      height: 100%;
      display: flex;
      align-items: center;
    }
  }
  .van-icon {
    margin-right: 0.1rem;
  }
  .btn-common {
    border-radius: 0.1rem;
    height: 0.6rem;
    line-height: 0.6rem;
    font-size: 0.3rem;
    width: auto;
    padding: 0;
    width: 1.7rem;
  }
  .emoji-mart {
    border: none;
    height: 3rem;
    transition: all 0.1s;
    width: 100%!important;
    /deep/ .emoji-mart-category-label {
      display: none;
    }
  }
}
/deep/ .van-empty{
  padding: .3rem 0;
}
/deep/ .van-empty__image{
  display: none;
}
</style>
